package com.wtwd.device.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.device.model.vo.PageDataVO;
import com.wtwd.device.model.vo.ResultVO;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.model.entity.*;
import com.wtwd.device.model.vo.GetGroupDialVo;
import com.wtwd.device.model.vo.GroupInfoVo;
import com.wtwd.device.model.vo.UploadFileVO;
import com.wtwd.device.service.GroupDialService;
import com.wtwd.device.service.GroupInfoService;
import com.wtwd.device.utils.GetCurrentSysUserInfoUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mjy
 * @since 2023-01-03
 */
@Api(tags = "分组模块")
@RestController
@RequestMapping("/group-info")
public class GroupInfoController {


    @Resource
    private GroupInfoService groupInfoService;


    @Resource
    private GroupDialService groupDialService;

    @Autowired
    private GetCurrentSysUserInfoUtils getCurrentSysUserInfoUtils;


    @Value("${file.http}")
    private String fileHttp;
    @Value("${dial.preview.image}")
    private String previewImg;
    @Value("${dial.file}")
    private String dialFile;
    @Value("${groupName.excel}")
    private String groupNamePath;
    @Value("${file.path}")
    private String filePath;

    /**
     * 分页获取分组列表
     *
     * @param currentPage
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation(value = "分页获取分组列表", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "int")
            , @ApiImplicitParam(name = "pageSize", value = "页面大小", required = true, dataType = "int")
            , @ApiImplicitParam(name = "name", value = "分组名称全模糊查询", required = false, dataType = "int")
    })
    @GetMapping("/getGroupInfoByConditionPage")
    public ResultVO<PageDataVO<GroupInfoSelectVo>> getGroupInfoByConditionPage(@RequestParam("currentPage") int currentPage,
                                                                               @RequestParam("pageSize") int pageSize,
                                                                               @RequestParam(value = "name", required = false) String name) {
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return ResultVO.error(RespCode.TOKEN_UNAUTHORIZED);
        }
        Page<GroupInfo> page = new Page<>(currentPage, pageSize);
        IPage groupInfos = groupInfoService.getGroupInfoByConditionPage(sysUser.getCustomerId(), name, page);
        List<GroupInfoSelectVo> groupInfoVos = new ArrayList<>();
        groupInfos.getRecords().stream().forEach(e -> {
            GroupInfo groupInfo = (GroupInfo) e;
            GroupInfoSelectVo groupInfoVo = new GroupInfoSelectVo();
            BeanUtils.copyProperties(groupInfo, groupInfoVo);
            if (StringUtils.isNotBlank(groupInfo.getLanguageFile()))
            groupInfoVo.setPath(fileHttp.concat(groupNamePath.concat(groupInfo.getLanguageFile())));
            groupInfoVos.add(groupInfoVo);
        });
        groupInfos.setRecords(groupInfoVos);
        return ResultVO.success(RespCode.SUCCESS, groupInfos);
    }

    /**
     * 查询分组详情
     *
     * @param currentPage
     * @param pageSize
     * @param groupId
     * @param dialName
     * @param watchId
     * @return
     */
    @ApiOperation(value = "查询分组详情", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "int")
            , @ApiImplicitParam(name = "pageSize", value = "页面大小", required = true, dataType = "int")
            , @ApiImplicitParam(name = "groupId", value = "分组id", required = true, dataType = "int")
            , @ApiImplicitParam(name = "dialName", value = "表盘名称", required = false, dataType = "String")
            , @ApiImplicitParam(name = "watchId", value = "手表类型", required = false, dataType = "String")
    })
    @GetMapping("/getGroupDialPage")
    public ResultVO<PageDataVO<GetGroupDialVo>> getGroupDialPage(@RequestParam("currentPage") int currentPage,
                                                                 @RequestParam("pageSize") int pageSize,
                                                                 @RequestParam(value = "groupId") Integer groupId,
                                                                 @RequestParam(value = "dialName", required = false) String dialName,
                                                                 @RequestParam(value = "watchId", required = false) String watchId
    ) {
        Page<GroupInfo> page = new Page<>(currentPage, pageSize);
        IPage<GetGroupDialVo> groupDialVoIPage = groupInfoService.getGroupDialPage(groupId, dialName, watchId, page);
        return ResultVO.success(RespCode.SUCCESS, groupDialVoIPage);
    }


    /**
     * 添加分组
     *
     * @param addGroupInfoDto
     * @return
     */
    @ApiOperation(value = "添加分组详情", notes = "")
    @PostMapping("/addGroupInfo")
    public ResultVO addGroupInfo(@RequestBody AddGroupInfoDto addGroupInfoDto) {
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return ResultVO.error(RespCode.TOKEN_UNAUTHORIZED);
        }
        AddGroupInfoCode addGroupInfoCode = groupInfoService.addGroupInfo(addGroupInfoDto.getGroupName(), sysUser.getCustomerId(), addGroupInfoDto.getPath());
        if (addGroupInfoCode.isRest()) {
            return ResultVO.success(RespCode.SUCCESS);
        } else {
            return ResultVO.error(addGroupInfoCode.getRespCode());
        }
    }

    @ApiOperation(value = "修改分组名称,或者修改语言文件", notes = "")
    @PostMapping("/updateGroupName")
    public ResultVO updateGroupName(@RequestBody UpdateGroupNameDto updateGroupNameDto) {
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return ResultVO.error(RespCode.TOKEN_UNAUTHORIZED);
        }
        boolean rest = groupInfoService.updateGroupName(updateGroupNameDto.getGroupId(), updateGroupNameDto.getName(), updateGroupNameDto.getPath(), sysUser.getCustomerId());
        if (rest) {
            return ResultVO.success(RespCode.SUCCESS);
        } else {
            return ResultVO.error(RespCode.GROPU_NAME_EXIST);
        }
    }


    /**
     * 删除分组
     *
     * @param deleteGroupDto
     * @return
     */
    @ApiOperation(value = "删除分组", notes = "")
    @PostMapping("/deleteGroup")
    public ResultVO deleteGroup(@RequestBody DeleteGroupDto deleteGroupDto) {
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return ResultVO.error(RespCode.TOKEN_UNAUTHORIZED);
        }
        Boolean rest = groupInfoService.deleteGroup(deleteGroupDto.getGroupInfoId());
        if (rest) {
            return ResultVO.success(RespCode.SUCCESS);
        } else {
            return ResultVO.error(RespCode.FAILED);
        }
    }


    /**
     * 切换排序
     *
     * @param switchingSortDto
     * @return
     */
    @ApiOperation(value = "切换排序", notes = "")
    @PostMapping("/switchingSort")
    public ResultVO switchingSort(@RequestBody SwitchingSortDto switchingSortDto) {
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return ResultVO.error(RespCode.TOKEN_UNAUTHORIZED);
        }
        boolean rest = groupInfoService.switchingSort(switchingSortDto.getGroupId(), switchingSortDto.getSequence(), sysUser.getCustomerId());
        if (rest) {
            return ResultVO.success(RespCode.SUCCESS);
        } else {
            return ResultVO.error(RespCode.FAILED);
        }
    }


    /**
     * 批量添加表盘到分组
     *
     * @param addGroupDialDto
     * @return
     */
    @ApiOperation(value = "批量添加表盘到分组", notes = "")
    @PostMapping("/bathAddGroupDial")
    public ResultVO bathAddGroupDial(@RequestBody AddGroupDialDto addGroupDialDto) {
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return ResultVO.error(RespCode.TOKEN_UNAUTHORIZED);
        }
        List<Integer> groupIds = addGroupDialDto.getGroupIds();
        List<GroupDialDto> groupDialDtos = addGroupDialDto.getGroupDialDtos();
        groupInfoService.bathAddGroupDial(groupIds, groupDialDtos);
        return ResultVO.success(RespCode.SUCCESS);
    }

    /**
     * 移除分组
     *
     * @param removeGroupDto
     * @return
     */
    @ApiOperation(value = "移除分组", notes = "")
    @PostMapping("/removeGroup")
    public ResultVO removeGroup(@RequestBody RemoveGroupDto removeGroupDto) {
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return ResultVO.error(RespCode.TOKEN_UNAUTHORIZED);
        }
        groupDialService.deleteGroupDial(removeGroupDto.getGroupId(), removeGroupDto.getDialId());
        return ResultVO.success(RespCode.SUCCESS);
    }

    /**
     * 获取该用户所有分组
     *
     * @return
     */
    @ApiOperation(value = "获取该用户所有分组", notes = "")
    @GetMapping("/getUserAllGroupInfo")
    public ResultVO<List<GroupInfo>> getUserAllGroupInfo() {
        SysUser sysUser = getCurrentSysUserInfoUtils.getCurrentSysUserInfo();
        if (sysUser == null) {
            return ResultVO.error(RespCode.TOKEN_UNAUTHORIZED);
        }
        List<GroupInfo> groupInfos = groupInfoService.getGroupInfoByCustomerId(sysUser.getCustomerId());
        return ResultVO.success(RespCode.SUCCESS, groupInfos);
    }


    /**
     * 根据手表id获取表盘分组
     *
     * @param getGroupInfoByWatchIdDto
     * @return
     */
    @ApiOperation(value = "获取该用户所有分组,并获取按规则获取分组里面的图片", notes = "")
    @PostMapping("/getGroupInfoByWatchId")
    public ResultVO<List<GroupInfoVo>> getGroupInfoByWatchId(@RequestBody GetGroupInfoByWatchIdDto getGroupInfoByWatchIdDto) {
        if (getGroupInfoByWatchIdDto == null || StringUtils.isBlank(getGroupInfoByWatchIdDto.getWatchId())) {
            return ResultVO.error(RespCode.NO_PARAM);
        }
        List<GroupInfo> groupInfos = groupInfoService.getGroupInfoByWatchId(getGroupInfoByWatchIdDto.getWatchId(), getGroupInfoByWatchIdDto.getType());
        List<GroupInfoVo> groupInfoVos = new ArrayList<>();
        if (groupInfos != null && groupInfos.size() > 0) {
            //根据分组id,以及手表id获取表盘
            List<Integer> groupIds = groupInfos.stream().map(GroupInfo::getId).collect(Collectors.toList());
            List<GetGroupIdAndDialByGroupIds> getGroupIdAndDialByGroupIds = groupInfoService.getGroupIdAndDialByGroupIds(groupIds, getGroupInfoByWatchIdDto.getWatchId());
            for (GroupInfo groupInfo : groupInfos) {
                GroupInfoVo groupInfoVo = new GroupInfoVo();
                BeanUtils.copyProperties(groupInfo, groupInfoVo);
                List<DialManagement> dialManagements = new ArrayList<>();
                if (getGroupIdAndDialByGroupIds != null && getGroupIdAndDialByGroupIds.size() > 0) {
                    for (GetGroupIdAndDialByGroupIds getGroupIdAndDialByGroupId : getGroupIdAndDialByGroupIds) {
                        if (getGroupIdAndDialByGroupId.getGroupId().equals(groupInfo.getId())) {
                            DialManagement dialManagement = new DialManagement();
                            BeanUtils.copyProperties(getGroupIdAndDialByGroupId, dialManagement);
                            dialManagements.add(dialManagement);
                        }
                    }
                }
                groupInfoVo.setDialManagements(dialManagements);
                groupInfoVos.add(groupInfoVo);
            }
        }
        if (groupInfoVos != null && groupInfoVos.size() > 0) {//做截取操作
            for (GroupInfoVo groupInfoVo : groupInfoVos) {
                List<DialManagement> dialManagements = groupInfoVo.getDialManagements();
                if (dialManagements != null && dialManagements.size() > 0 && dialManagements.size() > getGroupInfoByWatchIdDto.getNum()) {
                    groupInfoVo.setDialManagements(dialManagements.subList(0, getGroupInfoByWatchIdDto.getNum()));
                }
            }
        }
        return ResultVO.success(RespCode.SUCCESS, groupInfoVos);
    }

    /**
     * 根据手表id获取表盘分组
     *
     * @param dialId
     * @return
     */
    @ApiOperation(value = "根据表盘id获取表盘分组", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dialId", value = "表盘id", required = true, dataType = "int")
    })
    @GetMapping("/getGroupInfoByDialId")
    public ResultVO<List<GroupInfo>> getGroupInfoByDialId(@RequestParam(value = "dialId") Integer dialId) {
        List<GroupInfo> groupInfos = groupInfoService.getGroupInfoByDialId(dialId);
        return ResultVO.success(RespCode.SUCCESS, groupInfos);
    }


    /**
     * 根据表盘id和分组id,获取表盘
     *
     * @param dao
     * @return
     */
    @ApiOperation(value = "根据表盘id和分组id,获取表盘", notes = "")
    @PostMapping("/getDialByWatchIdAndGroupIdPage")
    public ResultVO<List<DialManagement>> getDialByWatchIdAndGroupIdPage(@RequestBody GetDialByWatchIdAndGroupIdDto dao) {
        if (dao == null || StringUtils.isBlank(dao.getWatchId()) || dao.getGroupId() == null) {
            return ResultVO.error(RespCode.NO_PARAM);
        }
        List<DialManagement> dialManagements = groupInfoService.getDialByWatchIdAndGroupIdPage(dao.getGroupId(), dao.getWatchId(), dao.getCurrentPage(), dao.getPageSize());
        return ResultVO.success(RespCode.SUCCESS, dialManagements);
    }


    @ApiOperation(value = "上传分组名称文件", notes = "上传后返回文件路径")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataTypeClass = MultipartFile.class)
    @ApiResponses({@ApiResponse(code = 400, message = "参数错误")
    })
    @PostMapping("/uploadPortrait")
    public ResultVO<UploadFileVO> uploadPortrait(@RequestParam MultipartFile file) {
        UploadFileVO uploadFileVO = groupInfoService.uploadPortrait(file);
        return ResultVO.success(uploadFileVO);
    }

}

